package moviles.comprap;

import moviles.mundo.Comprap;
import moviles.mundo.Servicio;
import moviles.mundo.Tienda;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.comprap.R;

public class VerServicios extends Activity {
	
	private Spinner spCategoria;	
	private ListView listaServicios;
	private ListView listaTiendas;
	private ArrayAdapter<String> adapterCategoria;
	private ArrayAdapter<String> adapterListas;
	private Spinner listas;
	private Servicio service;
	private Tienda tienda;
	private String listaSelected;
	private Context context = this;
	private EditText textCantidad;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ver_servicios);
		inicializarDatos();	
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_ver_servicios, menu);
		return true;
	}
	
	
	private void inicializarDatos(){
		listaServicios= null;
		listas = null;
		listaTiendas = null;
		tienda = null;
		spCategoria = (Spinner)findViewById(R.id.spinnerVerCategoriasServ);
		adapterCategoria = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		adapterCategoria.addAll(Comprap.darInstancia().getCategoriasServiciosToString());
		       		
		spCategoria.setAdapter(adapterCategoria);	
		spCategoria.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
	        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
	        	actualizar();
	        }
	        public void onNothingSelected(AdapterView<?> parent) {
	        }
	    });		
	}
	
	//Actualiza la lista
		public void actualizar()
		{
			//Toast.makeText(this,"Selecciono: "+spCategoria.getSelectedItem(), Toast.LENGTH_SHORT).show();
			listaServicios = (ListView)findViewById(R.id.listViewServ);		
			listaServicios.setAdapter(new ServiciosItemAdapter(this, android.R.layout.simple_list_item_1, Comprap.darInstancia().buscarCategoriaServicio((String)spCategoria.getSelectedItem()).getServicios()));
				
			listaServicios.setClickable(true);
			listaServicios.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			  @Override
			  public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
			    Servicio o = (Servicio)listaServicios.getItemAtPosition(position);
			    service = o;
			    showDialog(o.getNombreServicio(),"",o);		    
			  }
			});		
		}	
	
		public void showDialog(String title, String message,Servicio ser) {
			
			final Dialog dialog = new Dialog(this);
			dialog.setContentView(R.layout.producto_dialog_msg);
			dialog.setTitle(title);
		
	         TextView text = (TextView) dialog.findViewById(R.id.textView1);
	         text.setText(""+ser.getPrecio());
	         TextView text2 = (TextView) dialog.findViewById(R.id.textView4);
	         text2.setText(""+ser.getDescripcion());     
	         ImageView img = (ImageView) dialog.findViewById(R.id.imageView1);
	         img.setImageResource(R.drawable.ic_launcher);        
	         textCantidad = (EditText) dialog.findViewById(R.id.editText1);
	         textCantidad.setText("1");
	         
	         listas = (Spinner)dialog.findViewById(R.id.spinner1);
	         adapterListas = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,Comprap.darInstancia().getListasToString());
	         listas.setAdapter(adapterListas);
	         listas.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
	 	        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
	 	        	String o = (String)listas.getSelectedItem();  
		 		    if (o.equals("<Crear Lista>")) {					
		 		    	showDialogLista();	 		    	
		 		    }}
	 	        public void onNothingSelected(AdapterView<?> parent) {
	 	        }
	 	    });		                 
	         
	        //boton de agregar a lista
	        Button agregar = (Button) dialog.findViewById(R.id.button1);
	        agregar.setOnClickListener(new OnClickListener() {
	        @Override
	            public void onClick(View v) {
	        		listaSelected = (String)listas.getSelectedItem();
	        		if (textCantidad.getText().toString().equals(""))
	        		{        			      			
	        			Toast.makeText(context,"Ingrese la cantidad del producto", Toast.LENGTH_SHORT).show();
	        		}else{
	        			if(textCantidad.getText().toString().matches("[0-9]+")&&textCantidad.getText().toString().length()<4) {
	        				dialog.dismiss();        		
	                		seleccionarTienda();
	        			} else {
	        				Toast.makeText(context,"Cantidad no valida", Toast.LENGTH_SHORT).show();
	        			}  
	        		}
	        		;}
	             });   
	        
	        Button atras = (Button) dialog.findViewById(R.id.button2);
	        atras.setOnClickListener(new OnClickListener() {
	        @Override
	            public void onClick(View v) {
	        		dialog.dismiss(); 
	        		;}
	             });
	        dialog.show();
	    }
		
	
		/**
	     * Dialogo de seleccionar tienda
	     */
	    public void seleccionarTienda() 
		{
	    	listaTiendas = new ListView(this);		    	    	
	    	final AlertDialog d = new AlertDialog.Builder(this)
	        .setView(listaTiendas)
	        .setTitle("Seleccionar Tienda")
	        .setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
	        .setNegativeButton(android.R.string.cancel, null)
	        .create();
		    listaTiendas.setAdapter(new TiendaItemAdapter(this, android.R.layout.simple_list_item_1, Comprap.darInstancia().darTiendasDeServicio(service)));
		    listaTiendas.setClickable(true);
		    listaTiendas.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			  @Override
			  public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				  tienda = (Tienda)listaTiendas.getItemAtPosition(position);
				  Toast.makeText(context,""+tienda.getNombreTienda()+" seleccionada", Toast.LENGTH_SHORT).show();			  
			  }
			});			    		    
		    d.setOnShowListener(new DialogInterface.OnShowListener() {
		        @Override
		        public void onShow(DialogInterface dialog) {
		            Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
		            b.setOnClickListener(new View.OnClickListener() {
		                @Override
		                public void onClick(View view) {
		                	if (tienda==null){ Toast.makeText(context,"Seleccione una tienda", Toast.LENGTH_SHORT).show();}
		                	else{
		                	Comprap.darInstancia().agregarServicio(listaSelected,service,Integer.parseInt(textCantidad.getText().toString()),tienda);     
		                	exitoso(); 
		                    d.dismiss();}
		                }
		            });
		        }
		    });		    
		  d.show();			
		}
		
		
	    public void exitoso(){
	    	Toast.makeText(this,"Servicio agregado a la lista", Toast.LENGTH_SHORT).show();   
		}
		
		public void actualizarListas()	{
			adapterListas = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,Comprap.darInstancia().getListasToString());
			listas.setAdapter(adapterListas);
		}
	    
	
		public void showDialogLista(){
			final EditText input = new EditText(this);		
			AlertDialog.Builder dialogoLista = new AlertDialog.Builder(this);
			dialogoLista.setTitle("Crear lista");
		    dialogoLista.setMessage("Nombre lista");
		    dialogoLista.setView(input);	
		    dialogoLista.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		    	@Override    
		    	public void onClick(DialogInterface dialog, int whichButton) {
		                Comprap.darInstancia().createLista((String)input.getText().toString());
		                actualizarListas();
		    	}
		       });
		       dialogoLista.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		                   // Do nothing.
		            }
		       });
		    dialogoLista.show();	
		    }
		
	//Botones inferiores
	
		public void buscador(View v) {
			onSearchRequested();
	    }
		
		public void opciones(View v) {
			finish();
	    	Intent intent = new Intent(this, Opciones.class);
	    	startActivity(intent);
	    }
		
		public void usuario(View v) {
			finish();
	    	Intent intent = new Intent(this, Usuario.class);
	    	startActivity(intent);
	    }
		
		public void home(View v) {
			finish();
			Intent intent = new Intent(this, MainActivity.class);
	    	startActivity(intent);
	    }
		
		public void verListas(View v) {finish();
	    	Intent intent = new Intent(this, VerListas.class);
	    	startActivity(intent);
	    }

}
